package com.sunseen.capacitormachine.modules.home;

import android.util.SparseIntArray;

import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.commumication.tcp.event.NodeOffLineEvent;
import com.sunseen.capacitormachine.commumication.tcp.event.PortOffLineEvent;
import com.sunseen.capacitormachine.data.Constant;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.data.bean.HolderBean;
import com.sunseen.capacitormachine.databinding.FragmentOffLineBinding;
import com.sunseen.capacitormachine.modules.home.adapter.HolderOffLineAdapter;
import com.sunseen.capacitormachine.modules.home.bean.HolderOffLineBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class OffLineFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_off_line;
    }

    private FragmentOffLineBinding binding;

    private SparseIntArray offLineHolderIdArray = new SparseIntArray();
    private HolderOffLineAdapter adapter;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        binding = (FragmentOffLineBinding) viewDataBinding;
        binding.toolBar.setNavigationOnClickListener((view) -> pop());
        adapter = new HolderOffLineAdapter(R.layout.layout_item_holder_off_line);
        binding.offLineHolderRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        binding.offLineHolderRv.setAdapter(adapter);
        binding.refreshBtn.setOnClickListener((v) -> {
            offLineHolderIdArray.clear();
            adapter.setNewData(new ArrayList<>());
        });
        EventBus.getDefault().register(this);
        EventBus.getDefault().post(new PortOffLineEvent(0, 0, 0, 0, 0, false));
    }

    /**
     * 红外模块检测到有端口掉线
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNodeOffLineEvent(NodeOffLineEvent event) {
        if (event.isOffLine()) {
            StringBuilder stringBuilder = new StringBuilder();
            SparseIntArray intArray = event.getNodeArray();
            for (int i = 0, size = intArray.size(); i < size; i++) {
                stringBuilder.append(intArray.get(i));
                stringBuilder.append('、');
            }
            if (event.getPortId() == 0) {
                binding.number1Tv.setText(stringBuilder);
            } else {
                binding.number2Tv.setText(stringBuilder);
            }
        } else {
            CharSequence charSequence = binding.number1Tv.getText();
            if (charSequence != null && charSequence.length() > 0) {
                if (event.getPortId() == 0) {
                    binding.number1Tv.setText("");
                } else {
                    binding.number2Tv.setText("");
                }
            }
        }
    }


    /**
     * 红外模块检测到有夹具掉线或异常
     * 链路编号 =（机号-1）*3+端口-1
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPortOffLine(PortOffLineEvent event) {
        updateOffLineHolderRv(event.getPortId(), event.getMachineId(), 1, event.getOffLineFlag1());
        updateOffLineHolderRv(event.getPortId(), event.getMachineId(), 2, event.getOffLineFlag2());
        updateOffLineHolderRv(event.getPortId(), event.getMachineId(), 3, event.getOffLineFlag3());
    }

    private void updateOffLineHolderRv(int portId, int machineId, int pos, int offLineType) {
        if (offLineType > 0) {
            int index = (machineId - 1) * 3 + pos - 1;
            /**红外电路板对应的数字号*/
            int machinePos = Constant.HardwarePosTable[portId][index];
            if (machinePos >= 0) {//排除掉默认的两个-1空位
                int holderPos = Constant.HolderPosTable[portId][index];
                HolderBean holderBean = DataUtil.holderList.get(holderPos);
                int holderId = holderBean.getHolderId();
                int indexOfHolderId = offLineHolderIdArray.indexOfValue(holderId);
                HolderOffLineBean holderOffLineBean = new HolderOffLineBean(holderId, machinePos, offLineType);
                if (indexOfHolderId >= 0) {
                    HolderOffLineBean offLineBean = adapter.getItem(indexOfHolderId);
                    if (offLineBean != null) {
                        if (offLineBean.getHolderPos() != machinePos
                                || offLineBean.getHolderOffLineType() != holderOffLineBean.getHolderOffLineType()) {
                            adapter.setData(indexOfHolderId, holderOffLineBean);
                        }
                    }
                } else {
                    offLineHolderIdArray.append(offLineHolderIdArray.size(), holderId);
                    adapter.addData(holderOffLineBean);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
